var codeParams = {
  time: 60,
  bol: true,
  phone: '',
  code: '',
  name: '',
  city: '',
  date: '',
  note: '活动号：' + activityNo + '，photoplus试用申请咨询'
}

$(tryInit)

function tryInit() {
  // 试用
  $('#try').click(goTry);
  $('#code-button').click(getCode);
  $('#submit-button').click(submit);
}

// 试用弹窗
function goTry() {
  window.location.href = 'http://www.photoplus.cn';
}

function getCode() {
  codeParams.phone = $('#phone').val();

  var isPhone = checkPhone(codeParams.phone);
  console.log(isPhone);
  if (!isPhone) {
    toast('请填写正确的手机号');
    return;
  }
  if (codeParams.bol) {
    codeParams.time = 60;
    codeParams.bol = false;
    timerStatus();
    timer();

    $.ajax({
      url: '/home/code/send',
      type: 'post',
      dataType: 'json',
      data: {
        phone: codeParams.phone,
      },
      success: function(res) {
        if (res.success) {
          toast('验证码已发送');
        } else {
          toast('发送失败，稍后重试');
        }
      }
    })
  }
}

function submit() {
  var submitActive = $('#submit-button').hasClass('active');
  if (!submitActive) {

    codeParams.code = $('#code').val();
    codeParams.phone = $('#phone').val();
    codeParams.name = $('#name').val();
    // codeParams.date = Date.parse(new Date($('#date').val()));

    var isPhone = checkPhone(codeParams.phone);
    if (!codeParams.name) {
      toast('请输入您的姓名');
      return;
    }
    if (!isPhone) {
      toast('请填写正确的手机号');
      return;
    }
    $('#submit-button').addClass('active');
    $('.submit-loading').removeClass('none');
    $.ajax({
      url: '/home/book/order',
      type: 'post',
      dataType: 'json',
      data: {
        phone: codeParams.phone,
        verifyCode: codeParams.code,
        userName: codeParams.name,
        city: codeParams.city,
        note: codeParams.note
      },
      success: function(res) {
        if (res.success) {
          $('.submit-wrap').addClass('none');
          $('.success-wrap').removeClass('none');
        } else {
          toast(res.message);
        }
        $('#submit-button').removeClass('active');
        $('.submit-loading').addClass('none');
      }
    })
  }
}

function timerStatus() {
  if (codeParams.bol) {
    $('#code-button').removeClass('active');
    $('#code-button').html('获取验证码');
  } else {
    $('#code-button').addClass('active');
  }
}

function timer() {
  codeParams.time--;
  $('#code-button').html(codeParams.time + 's');
  if (codeParams.time !== 0) {
    setTimeout(timer, 1000);
  } else {
    codeParams.bol = true;
    timerStatus();
  }
}

function checkPhone (str) {
  var reg = /^1\d{10}$/
  if (str === '') {
    return false;
  } else {
    return reg.test(str.trim());
  }
}
